package com.atguigu.lease.web.admin.service.impl;

//import com.atguigu.lease.common.minio.MinioProperties;


import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileServer;
import io.minio.*;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.XmlParserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.rmi.ServerException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringJoiner;
import java.util.UUID;

/**
 * @author 86188
 * @version v1.0
 * @project ShangTingApartment
 * @Date 2025/7/8 14:14
 * @company []
 * @description
 */
@Service
public class FileServerImpl implements FileServer {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

//    @Override
//    public String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
//        MinioProperties minioProperties1 = MinioUtils.getMinioProperties();
//        String bucketName = minioProperties1.getBucketName();
//        //登录
//        MinioUtils.getMinioClient();
//        //判断是否存在我们需要的桶
//        boolean bucketExists = MinioUtils.bucketExists(bucketName);
//        if (!bucketExists){
//            //创建桶并设置规则
//            MinioUtils.createBucket(bucketName);
//        }
//        String url = MinioUtils.updatePutObject(file);
//        return url;
//    }
    @Override
    public String upload(MultipartFile file) throws ServerException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InternalException, io.minio.errors.ServerException, InsufficientDataException, io.minio.errors.ErrorResponseException, InternalException, InvalidResponseException, XmlParserException {
        //minio的登录
        //2.判断是否存在我们需要的桶
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        //3.不存在，创建桶，并且设置访问的策略
        if (!bucketExists){
            //创建一个桶
            minioClient.makeBucket(MakeBucketArgs.builder().build());
            //设置访问权限
            String config = """
                    {
                              "Statement" : [ {
                                "Action" : "s3:GetObject",
                                "Effect" : "Allow",
                                "Principal" : "*",
                                "Resource" : "arn:aws:s3:::lease/*"
                              } ],
                              "Version" : "2012-10-17"
                        }
                    """;
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(config).build());
        }
        //文件名优化
        String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID().toString() + "_";
        file.getOriginalFilename();

        //3. 存在 不用管
        //4. 向桶中上传对象即可
        System.out.println(file.getOriginalFilename());
        //minioClient.uploadObject(UploadObjectArgs.builder().bucket(minioProperties.getBucketName()).object(objectName).contentType(file.getContentType()).build());
        minioClient.putObject(PutObjectArgs.builder().
                bucket(minioProperties.getBucketName()).object(objectName).contentType(file.getContentType())
                /*
                参数1：上传文件的输入流
                参数2：文件的字节大小
                参数3：partSize文件是否切割上传！ 1GB 5*1024*1024 +(自己配置切块) 0（不切块） -1（自动切块）
                 */
                .stream(file.getInputStream(),file.getSize(),-1).build());
        //5拼接访问地址【端点+/+桶+/+对象名】
        String url = String.join("/", minioProperties.getEndPoint(), minioProperties.getBucketName(), objectName);
        return url;
    }
}
